import cv2
import copy
import os
import numpy as np
import time

from config.config_setting import logger, SAVE_TIMESTAP, SCREENSHOT_IDX, GAP_SECOND, repeti_retio, RESULT_IMAGE_PATH
from config.getConfigData import upload_det_result
# import read_config
"""图片工具包，用来删除重复图片和保存图片"""


# 删除重复图片
def cal_ahash_code(img):
    # print(img.shape, '=======')
    # c, h, w = img[0].shape
    cur_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    s_img = cv2.resize(cur_gray, dsize=(31, 18))  # dsize越大，越能分辨出细致的差别；此处是根据1280，720的比例
    img_mean = cv2.mean(s_img)
    return s_img > img_mean[0]


def cal_hamming_distance(model_hash_code, search_hash_code):
    # 返回不相同的个数
    diff = np.uint8(model_hash_code^search_hash_code)
    return cv2.countNonZero(diff)


# 保存图片
def save_data(img_local_path, img_name, img_save):
    if not os.path.exists(img_local_path):
        os.makedirs(img_local_path)
    save_image_path = img_local_path + '/' + img_name + '.jpg'
    logger.info("ssss"*10 + save_image_path)
    cv2.imwrite(save_image_path, img_save)


def save_image(img, device, algo, ori_i):
    cur_img_code = cal_ahash_code(img)
    try:
        b_time = SAVE_TIMESTAP[device][algo]
        if time.time() - b_time > GAP_SECOND:  # 如果两张违规截图保存的时间间隔大于指定时间，则执行保存操作
            pre_img_code = copy.deepcopy(SCREENSHOT_IDX[device][algo])
            # 如果前后两张违规截图相似度大于指定的值，则执行保存操作
            icr = cal_hamming_distance(pre_img_code, cur_img_code)
            if icr >= repeti_retio:
                img_local_path = os.path.join(RESULT_IMAGE_PATH, 'deviceId', str(device))
                img_name, img_time = time.strftime(str(algo)+'%Y%m%d%H%M%S'), time.strftime('%Y-%m-%d %H:%M:%S')  # 算法id+时间的格式

                save_data(img_local_path, img_name, img)  # 保存图片到指定路径
                save_data(os.path.join(RESULT_IMAGE_PATH, 'deviceId/save_original_image'), img_name, ori_i)  # 保存图片到指定路径
                upload_det_result(algo, img_time, device, img_name, img_local_path)  # 将截图路径上传到前端
                SCREENSHOT_IDX[device][algo], SAVE_TIMESTAP[device][algo] = cur_img_code, int(time.time())
            else:
                SCREENSHOT_IDX[device][algo], SAVE_TIMESTAP[device][algo] = cur_img_code, int(time.time())
        else:
            pass
    except:
        logger.info('May first frame ')
        SCREENSHOT_IDX[device][algo], SAVE_TIMESTAP[device][algo] = cur_img_code, int(time.time())


